package com.rongshu.view.home.fragment.child;

import android.animation.Animator;
import android.app.Dialog;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.rongshu.R;
import com.rongshu.eventbus.AddAttention;
import com.rongshu.eventbus.AttentionStateChange;
import com.rongshu.eventbus.ChangeTextSize;
import com.rongshu.eventbus.CleanCommentEphemeralData;
import com.rongshu.eventbus.CleanKeyBoard;
import com.rongshu.eventbus.HeaderClick;
import com.rongshu.eventbus.PlatformToShare;
import com.rongshu.eventbus.PostComment;
import com.rongshu.eventbus.ReceiverScreenEvent;
import com.rongshu.eventbus.ScrollToCommentDistrict;
import com.rongshu.eventbus.SetInput;
import com.rongshu.eventbus.UpdateCommmentCount;
import com.rongshu.utils.AnimationUtil;
import com.rongshu.utils.Common;
import com.rongshu.utils.Constant;
import com.rongshu.utils.ControlScrollLayoutManager;
import com.rongshu.utils.DateUtils;
import com.rongshu.utils.GlideUtils;
import com.rongshu.utils.LoginUtils;
import com.rongshu.utils.SpannableStringUtils;
import com.rongshu.utils.UserInfoUtils;
import com.rongshu.view.base.BaseActivity;
import com.rongshu.view.base.BaseFragment;
import com.rongshu.view.base.mvp.INetBean;
import com.rongshu.view.discovery.activity.UserHomePageActivity;
import com.rongshu.view.discovery.bean.ArticleDetaisRequest;
import com.rongshu.view.discovery.bean.AuthorDetailBean;
import com.rongshu.view.home.activity.LookMoreRecommendActivity;
import com.rongshu.view.home.activity.PreviewImgActivity;
import com.rongshu.view.home.activity.SingleArticleDetailsActivity;
import com.rongshu.view.home.adapter.ArticleDetailsRecomendAdapter;
import com.rongshu.view.home.adapter.CommentAdapter;
import com.rongshu.view.home.contract.ArticleDetailsView;
import com.rongshu.view.home.entity.ArticleItem;
import com.rongshu.view.home.entity.CommentDetails;
import com.rongshu.view.home.entity.CommentReplysBean;
import com.rongshu.view.home.entity.ContentClass;
import com.rongshu.view.home.entity.RecomendMsg;
import com.rongshu.view.home.entity.RecommendClass;
import com.rongshu.view.home.entity.RecommendResponse;
import com.rongshu.view.home.entity.UserAttention;
import com.rongshu.view.home.entity.UserProps;
import com.rongshu.view.home.fragment.dialog.CatalogueDialog;
import com.rongshu.view.home.fragment.dialog.PeopleRecommendDialog;
import com.rongshu.view.home.fragment.dialog.RecommendDialog;
import com.rongshu.view.home.fragment.dialog.SharePenpalAndThirdDialog;
import com.rongshu.view.home.listener.OnItemFunctionClickListener;
import com.rongshu.view.home.listener.OnRecommendClickListener;
import com.rongshu.view.home.presenter.ArticleDetailsPresenter;
import com.rongshu.view.home.widget.SelectableTextView;
import com.rongshu.view.penpal.bean.PenpalResponse;
import com.rongshu.view.userInfo.activity.PersonDetailsActivity;
import com.rongshu.widget.BanyanDialog;
import com.rongshu.widget.YNestedScrollView;
import com.rongshu.widget.xrichtext.RichTextView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.utils.DensityUtil;
import com.utils.FastClickUtils;
import com.utils.LogUtil;
import com.utils.SPUtils;
import com.utils.StringUtils;
import com.utils.constants.SPKey;
import com.widget.CircleImageView;
import com.widget.dialog.BottomListDialog;
import com.widget.loading.AnimatorListener;
import com.widget.toast.ToastUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.disposables.Disposable;
import okhttp3.ResponseBody;

import static android.app.Activity.RESULT_OK;
import static android.content.Context.CLIPBOARD_SERVICE;
import static com.rongshu.utils.UserInfoUtils.getUserId;

/**
 * 个别数据没有及时更新
 */
public class ArticleDetailsFragment extends BaseFragment<ArticleDetailsPresenter> implements ArticleDetailsView, OnItemFunctionClickListener {
    @BindView(R.id.smartRefreshLayout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.nested_scroll_view)
    YNestedScrollView nested_scroll_view;
    @BindView(R.id.layout_cover)
    RelativeLayout layout_cover;
    @BindView(R.id.layout_recommend_details)
    RelativeLayout layout_recommend_details;
    @BindView(R.id.iv_cover)
    ImageView iv_cover;
    @BindView(R.id.layout_body)
    RelativeLayout layout_body;
    @BindView(R.id.layout_author_name_heat_attention)
    RelativeLayout layout_author_name_heat_attention;
    @BindView(R.id.txt_article_title)
    TextView txt_article_title;//标题
    @BindView(R.id.iv_corpus)
    ImageView iv_corpus;//目录
    @BindView(R.id.iv_head_icon)
    CircleImageView iv_head_icon;//头像
    @BindView(R.id.iv_vip)
    ImageView iv_vip;
    @BindView(R.id.layout_statistics)
    LinearLayout layout_statistics;
    @BindView(R.id.txt_article_author)
    TextView txt_article_author;//作者
    @BindView(R.id.layout_add_attention)
    RelativeLayout layout_add_attention;//关注
    @BindView(R.id.txt_read_time)
    TextView txt_read_time;
    @BindView(R.id.txt_subject)
    SelectableTextView txt_subject;//编者
    @BindView(R.id.txt_content)
    RichTextView txt_content;//内容
    @BindView(R.id.txt_editor)
    TextView txt_editor;//编者
    @BindView(R.id.txt_editor_data)
    TextView txt_editor_data;//编者日期。
    @BindView(R.id.flowlayout)
    LinearLayout flowlayout;//兴趣
    @BindView(R.id.layout_keyword_first)
    FrameLayout layout_keyword_first;
    @BindView(R.id.txt_keyword_first)
    TextView txt_keyword_first;
    @BindView(R.id.layout_keyword_second)
    FrameLayout layout_keyword_second;
    @BindView(R.id.txt_keyword_second)
    TextView txt_keyword_second;
    @BindView(R.id.layout_keyword_third)
    FrameLayout layout_keyword_third;
    @BindView(R.id.txt_keyword_third)
    TextView txt_keyword_third;
    @BindView(R.id.layout_keyword_four)
    FrameLayout layout_keyword_four;
    @BindView(R.id.txt_keyword_four)
    TextView txt_keyword_four;
    @BindView(R.id.layout_chapter)
    LinearLayout layout_chapter;//上下目录all
    @BindView(R.id.layout_last)
    RelativeLayout layout_last;//上一张
    @BindView(R.id.iv_last)
    ImageView iv_last;
    @BindView(R.id.txt_last)
    TextView txt_last;
    @BindView(R.id.layout_catalog)
    RelativeLayout layout_catalog;//目录
    @BindView(R.id.layout_next)
    RelativeLayout layout_next;//下一张
    @BindView(R.id.iv_next)
    ImageView iv_next;
    @BindView(R.id.txt_next)
    TextView txt_next;
    @BindView(R.id.layout_recommend)
    RelativeLayout layout_recommend;//推荐语all
    @BindView(R.id.txt_see_more)
    TextView txt_see_more;//查看更多
    @BindView(R.id.iv_next_icon)
    ImageView iv_next_icon;
    @BindView(R.id.rv_recommend)
    RecyclerView rv_recommend;
    @BindView(R.id.iv_author_icon)
    ImageView iv_author_icon;
    @BindView(R.id.layout_splendid_comment)
    RelativeLayout layout_splendid_comment;
    @BindView(R.id.rv_comment)
    RecyclerView rv_comment;//评论区
    @BindView(R.id.layout_empty)
    RelativeLayout layout_empty;//无评论

    //bundle
    private ArticleItem articleItem = null;
    //map
    private Map<String, Object> map = null;
    //pageIndex
    private int pageIndex = 1;
    //pageSize
    private int pageSize = 10;
    //adapter
    private ArticleDetailsRecomendAdapter mArticleDetailsRecomendAdapter = null;
    //adapter
    private CommentAdapter mCommentAdapter = null;
    //评论的数据集合
    private List<CommentDetails.ResponseBean> mCommentDetails = null;
    //isLoadMore
    private boolean isLoadMore = false;
    //intent
    private Intent intent = null;
    //进入他人主页
    private final int REQUEST_OTHER = 0x01;
    //登录标识
    public static final int REQUEST_LOGIN = 0X0A;
    //评论
    private int comment_id = 0, reply_id = 0;
    //local_position 局部刷新position
    private int local_position;
    private int reply_pageIndex = 1;
    private int reply_pageSize = 100;
    //评论点赞position
    private int likePosition = 0;
    //是否删除为回复
    private boolean isDeteleReply = false;
    //删除评论回复的position
    private int replyPosition = 0;
    //fragment显示隐藏
    private boolean hiddon;
    //评论
    //@的用戶信息
    private LinkedHashMap<String, AuthorDetailBean> authorDetailBeanMap = null;
    //offsetDistance
    private int offsetDistance = 0;
    private Disposable disposable;
    //复制，回复，删除dialog
    private List<String> functions = null;
    //赞赏推荐保留的文字
    private String recomendContent = null;
    //touch 过程不进行记录
    private boolean isTouch = false;
    //scrollY
    private int mScrollY = 0;
    //bodyLocation
    private int lastBodyLocation = 0;
    //commentLocation
    private int lastCommentLocation = 0;
    //是否从他人主页返回
    private boolean isOtherHomePagerReturn = false;
    //滑动标识
    private final int scrollMessage = 0x0e;
    //hander
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case scrollMessage:
                    handler.removeMessages(scrollMessage);
                    if (mScrollY == nested_scroll_view.getScrollY()) {
                        LogUtil.i("onScrollChange", "自动滑动停止了");
                        isTouch = false;
                        return;
                    }
                    handler.sendEmptyMessageDelayed(scrollMessage, 1000);
                    break;
            }
        }
    };

    @Override
    protected int attachLayoutRes() {
        return R.layout.fragment_article_details_view;
    }

    @Override
    protected void initViews() {
        setPresenter(new ArticleDetailsPresenter(getActivity()), this);
        //bundle
        if (getArguments() != null) {
            articleItem = (ArticleItem) getArguments().getSerializable(Constant.INTENT_DATA);
            updateArticle();
        }
        //refreshlayout
        refreshLayout.setEnableRefresh(false);
        refreshLayout.setEnableHeaderTranslationContent(false);
        refreshLayout.setEnableAutoLoadmore(true);
        refreshLayout.setOnLoadmoreListener(new OnLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                isLoadMore = true;
                pageIndex++;
                getCommentMsg();
                refreshLayout.finishLoadmore(5000, true);
            }
        });
        //推荐语
        mArticleDetailsRecomendAdapter = new ArticleDetailsRecomendAdapter(getActivity());
        mArticleDetailsRecomendAdapter.setHasStableIds(true);
        //recyclerView
        ControlScrollLayoutManager manager1 = new ControlScrollLayoutManager(getActivity());
        rv_recommend.setLayoutManager(manager1);
        rv_recommend.setAdapter(mArticleDetailsRecomendAdapter);
        rv_recommend.setFocusable(false);
        rv_recommend.setFocusableInTouchMode(false);
        rv_recommend.setNestedScrollingEnabled(false);
        //评论
        mCommentDetails = new ArrayList<>();
        mCommentAdapter = new CommentAdapter(getActivity());
        mCommentAdapter.setResponseBeanList(mCommentDetails);
        mCommentAdapter.setOnItemFunctionClickListener(this);
        mCommentAdapter.setHasStableIds(true);
        //recyclerView
        ControlScrollLayoutManager manager2 = new ControlScrollLayoutManager(getActivity());
        rv_comment.setLayoutManager(manager2);
        rv_comment.setAdapter(mCommentAdapter);
        rv_comment.setFocusable(false);
        rv_comment.setFocusableInTouchMode(false);
        rv_comment.setNestedScrollingEnabled(false);
        offsetDistance = (int) getContext().getResources().getDimension(R.dimen.dd_dimen_160px);
        //nested_scroll_view listener
        nested_scroll_view.setOnScrollChangeListener(new YNestedScrollView.OnScrollChangeListener() {
            @Override
            public void onScrollChange(YNestedScrollView v, int scrollX, int scrollY, int oldScrollX, int oldScrollY) {
                if (!hiddon) {
                    return;
                }
                mScrollY = scrollY;
                //通知父类进行操作Toolbar
                int toolbarHeight = DensityUtil.getStateBar(getActivity()) + getResources().getDimensionPixelSize(R.dimen.dd_dimen_90px);
                //标题头部的位置
                int title_location = layout_body.getTop() - toolbarHeight;
                //头像底部的位置
                int head_location = layout_body.getTop() + layout_author_name_heat_attention.getBottom() - toolbarHeight;
                //评论的位置
                int commentLocation = (int) (layout_splendid_comment.getTop() - v.getMeasuredHeight() + 1.2 * offsetDistance);
                EventBus.getDefault().post(new ReceiverScreenEvent(scrollY, oldScrollY, title_location, head_location, commentLocation));
                if (!isTouch) {
                    if (scrollY >= layout_splendid_comment.getTop() - nested_scroll_view.getMeasuredHeight() + 1.2 * offsetDistance) {
                        LogUtil.i("onScrollChange", "已经滑到评论了");
                        lastCommentLocation = scrollY;
                    } else {
                        LogUtil.i("onScrollChange", "已经滑到正文了");
                        lastBodyLocation = scrollY;
                    }
                } else {
                    handler.sendEmptyMessageDelayed(scrollMessage, 1000);
                }
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    protected void updateViews(boolean isRefresh) {
        getRecommendMsg();
        getCommentMsg();
        getIsGuanZhu();
    }

    /**
     * 获取推荐语
     */
    private void getRecommendMsg() {
        if (articleItem == null) {
            return;
        }
        map = new HashMap<>();
        map.put("contribute_id", articleItem.getContribute_id());
        map.put("contribute_type", 1);
        map.put("pageIndex", 1);
        map.put("pageSize", 3);
        presenter.getRecommendMsg(
                (int) map.get("contribute_id"),
                (int) map.get("contribute_type"),
                (int) map.get("pageIndex"),
                (int) map.get("pageSize"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 获取文章详情下的评论
     */
    private void getCommentMsg() {
        int user_id = getUserId();
        if (articleItem == null) {
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", articleItem.getContribute_id());
        map.put("Sort", 0);
        map.put("pageIndex", pageIndex);
        map.put("pageSize", pageSize);
        presenter.getCommentDetail((int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("Sort"),
                (int) map.get("pageIndex"),
                (int) map.get("pageSize"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 我的所有笔友会
     */
    public void getPenpalWillMsg() {
        //user_id
        int user_id = UserInfoUtils.getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin((BaseActivity) getActivity(),REQUEST_LOGIN);
            return;
        }
        //http
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("pageIndex", 1);
        map.put("pageSize", 100);
        presenter.getJoinedPenpal((int) map.get("user_id"),
                (int) map.get("pageIndex"),
                (int) map.get("pageSize"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 获取我是否关注过某一个用户
     */
    private void getIsGuanZhu() {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            return;
        }
        if (articleItem == null) {
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("ta_user_id", articleItem.getUser_id());
        presenter.getIsGuanZhu(
                (int) map.get("user_id"),
                (int) map.get("ta_user_id"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 关注
     */
    private void concernWith() {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin((BaseActivity) getActivity(),REQUEST_LOGIN);
            return;
        }
        if (articleItem == null) {
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", articleItem.getContribute_id());
        map.put("user_id_to", articleItem.getUser_id());
        presenter.concernWith(
                (int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("user_id_to"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 获取用户道具卡数量
     */
    private void getUserProps() {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin((BaseActivity) getActivity(),REQUEST_LOGIN);
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("propsType", 1);//1小众推荐卡，2大众推荐卡，3超级推荐卡,目前只传1
        presenter.getUserProps(
                (int) map.get("user_id"),
                (int) map.get("propsType"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 读者推荐
     * recommend_type
     */
    public void postRecommend(int recommend_type, int pay_type, String contents) {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin((BaseActivity) getActivity(),REQUEST_LOGIN);
            return;
        }
        if (articleItem == null) {
            return;
        }
        //http
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", articleItem.getContribute_id());
        map.put("contribute_type", 1);
        map.put("recommend_type", recommend_type);
        map.put("pay_device", 1);//手机设备(1.安卓 2.ios)
        map.put("pay_type", pay_type);
        RecommendClass recommendClass = new RecommendClass();
        recommendClass.setContents(contents);
        presenter.postRecommend(
                (int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("contribute_type"),
                (int) map.get("recommend_type"),
                (int) map.get("pay_device"),
                (int) map.get("pay_type"),
                Common.encryptionSign(map),
                recommendClass);
        map.clear();
    }

    /**
     * 文章评论/评论回复/回复回复
     */
    private void postCommentOrReplyAdd(int comment_id, int reply_id, String content) {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin((BaseActivity) getActivity(),REQUEST_LOGIN);
            return;
        }
        if (articleItem == null) {
            return;
        }
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", articleItem.getContribute_id());
        map.put("comment_id", comment_id);
        map.put("reply_id", reply_id);
        ContentClass contentClass = new ContentClass();
        contentClass.setContents(content);
        contentClass.setTitle(null);
        StringBuilder aiteStrsb = new StringBuilder();
        for (Map.Entry<String, AuthorDetailBean> entry : authorDetailBeanMap.entrySet()) {
            if (!TextUtils.isEmpty(aiteStrsb)) {
                aiteStrsb.append(",");
            }
            aiteStrsb.append(entry.getValue().getUser_id_to());
        }
        contentClass.setAiteStr(aiteStrsb.toString());
        contentClass.setPenpalwill_id(null);
        presenter.postCommentOrReplyAdd((int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("comment_id"),
                (int) map.get("reply_id"),
                Common.encryptionSign(map),
                contentClass);
        map.clear();
    }

    /**
     * 获取单个评论下的所有回复
     */
    private void getOnecommentDetail(int comment_id) {
        int user_id = getUserId();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("comment_id", comment_id);
        map.put("pageIndex", reply_pageIndex);
        map.put("pageSize", reply_pageSize);
        presenter.getOnecommentDetail(user_id, comment_id, reply_pageIndex, reply_pageSize,
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 评论点赞（任何评论）
     */
    private void getCommentlike(int comment_id) {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin((BaseActivity) getActivity(),REQUEST_LOGIN);
            return;
        }
        if (articleItem == null) {
            return;
        }
        int obj_id = articleItem.getContribute_id();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("type", 1);//1文章，2帖子
        map.put("obj_id", obj_id);//文章ID或者帖子ID
        map.put("comment_id", comment_id);
        presenter.getCommentlike(
                (int) map.get("user_id"),
                (int) map.get("type"),
                (int) map.get("obj_id"),
                (int) map.get("comment_id"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 文章评论删除/回复删除
     */
    public void getCommentOrReplyDelete(int comment_id, int reply_id) {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin((BaseActivity) getActivity(),REQUEST_LOGIN);
            return;
        }
        if (articleItem == null) {
            return;
        }
        int contribute_id = articleItem.getContribute_id();
        map = new HashMap<>();
        map.put("user_id", user_id);
        map.put("contribute_id", contribute_id);
        map.put("comment_id", comment_id);
        map.put("reply_id", reply_id);
        presenter.getCommentOrReplyDelete(
                (int) map.get("user_id"),
                (int) map.get("contribute_id"),
                (int) map.get("comment_id"),
                (int) map.get("reply_id"),
                Common.encryptionSign(map));
        map.clear();
    }

    /**
     * 更新view
     */
    private void updateArticle() {
        if (articleItem == null) {
            return;
        }
        try {
            //头图
            int margin = DensityUtil.getStateBar(getActivity());
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) layout_body.getLayoutParams();
            String topImg = articleItem.getTopImg();
            boolean hasTopBg = TextUtils.isEmpty(topImg) ? true : false;
            if (hasTopBg) {
                layout_cover.setVisibility(View.GONE);
                layoutParams.topMargin = hasTopBg ?
                        margin + (int) getActivity().getResources().getDimension(R.dimen.dd_dimen_142px) :
                        (int) getActivity().getResources().getDimension(R.dimen.dd_dimen_50px);
                layout_body.setLayoutParams(layoutParams);
            } else {
                layout_cover.setVisibility(View.VISIBLE);
                layoutParams.topMargin = hasTopBg ?
                        margin + (int) getActivity().getResources().getDimension(R.dimen.dd_dimen_142px) :
                        (int) getActivity().getResources().getDimension(R.dimen.dd_dimen_50px);
                layout_body.setLayoutParams(layoutParams);
                ViewGroup.LayoutParams lp = iv_cover.getLayoutParams();
                lp.width = DensityUtil.getScreenWidth(getActivity());
                lp.height = lp.width / 4 * 3;
                iv_cover.setLayoutParams(lp);
                GlideUtils.loadImageView(getActivity(), iv_cover, topImg);
            }
            //类型
            int fontType = SPUtils.getPreferences(SPKey.FONTPATTERN, 1);
            //标题
            txt_article_title.setText(articleItem.getTitle());
            //目录
            iv_corpus.setVisibility(articleItem.getIsSerial() ? View.VISIBLE : View.GONE);
            layout_chapter.setVisibility(articleItem.getIsSerial() ? View.VISIBLE : View.GONE);
            //左右翻页图标
            int upChapter = articleItem.getUpChapter();
            int nextChapter = articleItem.getNextChapter();
            iv_last.setImageResource(articleItem.getIsSerial() && upChapter == 0 ? R.drawable.last_gray_icon : R.drawable.last_dark_icon);
            txt_last.setTextColor(articleItem.getIsSerial() && upChapter == 0 ?
                    getResources().getColor(R.color.color_f0f0f0) :
                    getResources().getColor(R.color.color_9f9f9f));
            iv_next.setImageResource(articleItem.getIsSerial() && nextChapter == 0 ? R.drawable.next_gray_icon : R.drawable.next_dark_icon);
            txt_next.setTextColor(articleItem.getIsSerial() && nextChapter == 0 ?
                    getResources().getColor(R.color.color_f0f0f0) :
                    getResources().getColor(R.color.color_9f9f9f));
            //头像
            RequestOptions options = new RequestOptions()
                    .placeholder(R.drawable.user_head_icon);
            Glide.with(this)
                    .load(articleItem.getAvatar())
                    .apply(options)
                    .into(iv_head_icon);
            //vip
            iv_vip.setVisibility(articleItem.isVip() ? View.VISIBLE : View.GONE);
            //作者
            txt_article_author.setText(articleItem.getBi_name());
            //关注
            layout_add_attention.setVisibility(articleItem.getUser_id() == UserInfoUtils.getUserId() ?
                    View.GONE : articleItem.getIsConcern() > 0 || articleItem.getIsSerial() ?
                    View.GONE : View.VISIBLE);//0没有关注，1已关注
            //字数，时间，热度
            String content = "字数  " + articleItem.getNumber() + "   阅读需 " + (int) Math.ceil(articleItem.getNumber() / 400.0) + " min   热度  " + articleItem.getHeatCount();
            //阅读数
            txt_read_time.setText(SpannableStringUtils.addAbsoluteSizeSpans(content, ContextCompat.getColor(getActivity(), R.color.color_4a4a4a)));
            //编者按
            setRedact_note(fontType);
            //内容
            final String details = articleItem.getContent();
            txt_content.setRtTextSize((int) getResources().getDimension(Constant.contentSizes[fontType]));
            txt_content.clearAllLayout();
            txt_content.post(new Runnable() {
                @Override
                public void run() {
                    presenter.dealWithContent(details);
                }
            });
            txt_content.setOnRtImageClickListener(new RichTextView.OnRtImageClickListener() {
                @Override
                public void onRtImageClick(String imagePath) {
                    if (articleItem == null) {
                        return;
                    }
                    ArrayList<String> list = new ArrayList<>();
                    String topImg = articleItem.getTopImg();
                    if (topImg != null) {
                        list.add(topImg);
                    }
                    List<String> imgList = txt_content.getImagePaths();
                    list.addAll(imgList);
                    intent = new Intent(getActivity(), PreviewImgActivity.class);
                    intent.putStringArrayListExtra(Constant.INTENT_DATA, list);
                    intent.putExtra(Constant.INTENT_MESSAGE, imagePath);
                    startActivity(intent);
                    getActivity().overridePendingTransition(0, 0);
                }
            });
            //编辑，时间
            txt_editor.setText("本文编辑：" + articleItem.getRedactName());
            String check_datetime = articleItem.getCheck_datetime();
            if (!TextUtils.isEmpty(check_datetime)) {
                txt_editor_data.setText(DateUtils.ConvertDate(check_datetime));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 编者按
     *
     * @param
     */
    public void setRedact_note(int fontType) {
        String redact_note = articleItem.getRedact_note();
        if (TextUtils.isEmpty(redact_note)) {
            txt_subject.setVisibility(View.GONE);
        } else {
            //编者按
            redact_note = "编者按：" + redact_note;
            txt_subject.setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) getResources().getDimension(Constant.contentSizes[fontType]));
            txt_subject.setText(redact_note);
        }
    }

    @OnClick({R.id.iv_head_icon, R.id.layout_add_attention, R.id.txt_recommend, R.id.txt_see_more, R.id.iv_next_icon,
            R.id.iv_corpus, R.id.layout_catalog, R.id.layout_last, R.id.layout_next, R.id.layout_cover})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_head_icon://头像
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                onHeaderClick();
                break;
            case R.id.layout_add_attention://加关注
                if (FastClickUtils.isFastClick()) {
                    return;
                }

                concernWith();
                break;
            case R.id.txt_recommend://支持推荐
                if (FastClickUtils.isFastClick()) {
                    return;
                }

                //获取用户道具卡数量
                getUserProps();
                break;
            case R.id.txt_see_more://查看更多
            case R.id.iv_next_icon:
                if (FastClickUtils.isFastClick()) {
                    return;
                }

                intent = new Intent(getActivity(), LookMoreRecommendActivity.class);
                if (articleItem != null) {
                    intent.putExtra(Constant.INTENT_DATA, articleItem.getContribute_id());
                    intent.putExtra(Constant.INTENT_MESSAGE, 1);
                }
                startActivity(intent);
                break;
            case R.id.iv_corpus://连载
            case R.id.layout_catalog:
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                showCatalogDialogFragment();
                break;
            case R.id.layout_last://连载上一章
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                if (articleItem == null) {
                    return;
                }
                int upChapter = articleItem.getUpChapter();
                if (upChapter == 0) {
                    toast("没有上一章了");
                    return;
                }
                catalogFlipOver(articleItem.getSerialize_id(), articleItem.getSort(), 1);
                break;
            case R.id.layout_next://连载下一章
                if (FastClickUtils.isFastClick()) {
                    return;
                }
                if (articleItem == null) {
                    return;
                }
                int nextChapter = articleItem.getNextChapter();
                if (nextChapter == 0) {
                    toast("没有下一章了");
                    return;
                }
                catalogFlipOver(articleItem.getSerialize_id(), articleItem.getSort(), 2);
                break;
            case R.id.layout_cover://头图
                if (articleItem == null) {
                    return;
                }
                String topImg = articleItem.getTopImg();
                if (topImg == null) {
                    return;
                }
                ArrayList<String> list = new ArrayList<>();
                list.add(topImg);
                List<String> imgList = txt_content.getImagePaths();
                list.addAll(imgList);
                intent = new Intent(getActivity(), PreviewImgActivity.class);
                intent.putStringArrayListExtra(Constant.INTENT_DATA, list);
                intent.putExtra(Constant.INTENT_MESSAGE, topImg);
                startActivity(intent);
                break;
        }
    }

    /**
     * 头像点击
     */
    private void onHeaderClick() {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin((BaseActivity) getActivity(),REQUEST_LOGIN);
            return;
        }
        if (articleItem == null) {
            return;
        }
        if (user_id == articleItem.getUser_id()) {
            intent = new Intent(getActivity(), PersonDetailsActivity.class);
            startActivity(intent);
        } else {
            intent = new Intent(getActivity(), UserHomePageActivity.class);
            intent.putExtra(Constant.USER_ID, articleItem.getUser_id());
            startActivityForResult(intent, REQUEST_OTHER);
        }
    }

    /**
     * 连载
     */
    public void showCatalogDialogFragment() {
        if (this.articleItem == null) {
            return;
        }
        CatalogueDialog.Builder builder = new CatalogueDialog.Builder(getActivity());
        builder.setSerialize_id(articleItem.getSerialize_id()).create().show();
    }

    /**
     * 连载翻页
     * serialize_id 连载ID
     * chapter 当前文章序号
     * type 1上一章，2下一章，3选中某一章
     */
    public void catalogFlipOver(int serialize_id, int chapter, int type) {
        intent = new Intent(getActivity(), SingleArticleDetailsActivity.class);
        ArticleDetaisRequest request = new ArticleDetaisRequest();
        request.setContribute_id(serialize_id);
        request.setChapter(chapter);
        request.setSerialize_flip_over_type(type);
        intent.putExtra(Constant.ARTICLE_DETAILS_REQUEST, request);
        startActivity(intent);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case REQUEST_OTHER://他人主页返回
                    if (articleItem == null) {
                        return;
                    }
                    isOtherHomePagerReturn = true;
                    getIsGuanZhu();
                    break;
            }
        }
    }

    /**
     * 推荐语返回集合
     *
     * @param responseBeanList
     */
    @Override
    public void onRecomendMsg(List<RecomendMsg.ResponseBean> responseBeanList) {
        if (responseBeanList.isEmpty()) {
            layout_recommend.setVisibility(View.GONE);
        } else {
            layout_recommend.setVisibility(View.VISIBLE);
            mArticleDetailsRecomendAdapter.setResponseBeanList(responseBeanList);
            mArticleDetailsRecomendAdapter.notifyDataSetChanged();
        }

        //查看更多显示隐藏
        if (responseBeanList.isEmpty() || responseBeanList.size() < 3) {
            iv_next_icon.setVisibility(View.GONE);
            txt_see_more.setVisibility(View.GONE);
        } else {
            iv_next_icon.setVisibility(View.VISIBLE);
            txt_see_more.setVisibility(View.VISIBLE);
        }

        //listener
        mArticleDetailsRecomendAdapter.setOnItemClickListener(new ArticleDetailsRecomendAdapter.OnItemClickListener() {
            @Override
            public void onClick(int position) {
                RecomendMsg.ResponseBean recomendMsg = mArticleDetailsRecomendAdapter.getResponseBeanList().get(position);
                int count = recomendMsg.getTotalCount();
                if (count > 1) {
                    if (articleItem != null && recomendMsg != null) {
                        showPeopleRecommendDialog(articleItem.getContribute_id(), 1, recomendMsg.getFrom_uid(),
                                recomendMsg.getFrom_Nmae(), recomendMsg.getAvatar(), recomendMsg.getTotalCount());
                    }
                }
            }
        });
    }

    /**
     * 个人推荐语列表dialog
     */
    private void showPeopleRecommendDialog(int contribute_id, int contribute_type, int from_uid,
                                           String from_Nmae, String avatar, int totalCount) {
        PeopleRecommendDialog.Builder builder = new PeopleRecommendDialog.Builder(getActivity());
        builder.setContribute_id(contribute_id)
                .setContribute_type(contribute_type)
                .setFrom_uid(from_uid)
                .setAvatar(avatar)
                .setFrom_Nmae(from_Nmae)
                .setTotalCount(totalCount)
                .create().show();
    }

    /**
     * 评论返回集合
     *
     * @param responseBeanList
     */
    @Override
    public void onCommentMsg(List<CommentDetails.ResponseBean> responseBeanList) {
        if (isLoadMore) {//加载更多
            if (responseBeanList == null || responseBeanList.isEmpty()) {
                refreshLayout.finishLoadmoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadmore();
            }
            this.mCommentDetails.addAll(responseBeanList);
        } else {//刷新
            layout_empty.setVisibility(responseBeanList == null || responseBeanList.size() == 0 ? View.VISIBLE : View.GONE);
            refreshLayout.setEnableLoadmore(responseBeanList == null || responseBeanList.size() == 0 ? false : true);
            this.mCommentDetails.addAll(responseBeanList);
        }
        mCommentAdapter.notifyDataSetChanged();
    }

    /**
     * 笔友会数据
     *
     * @param responseBeanList
     */
    @Override
    public void onPenpalWillMsg(List<PenpalResponse.ResponseBean> responseBeanList) {
        if (responseBeanList == null) {
            return;
        }
        share(responseBeanList);
    }

    /**
     * 获取我是否关注过某一个用户
     *
     * @param userAttention
     */
    @Override
    public void onIsConcernWith(UserAttention userAttention) {
        if (userAttention.getErrCode() == 0) {
            UserAttention.ResponseBean bean = userAttention.getResponse();
            if (bean == null || articleItem == null) {
                return;
            }
            int isGuanZhu = bean.getIs_guanzhu();
            if (isGuanZhu != -1) {
                articleItem.setIsConcern(isGuanZhu);
                int serialize_id = articleItem.getSerialize_id();
                if (serialize_id == 0) {//不是连载，可以更新关注状态
                    layout_add_attention.setVisibility(articleItem.getUser_id() == UserInfoUtils.getUserId() ?
                            View.GONE : articleItem.getIsConcern() > 0 ?
                            View.GONE : View.VISIBLE);//0没有关注，1已关注
                }
                EventBus.getDefault().post(new AttentionStateChange(articleItem.getIsConcern(), isOtherHomePagerReturn));
                isOtherHomePagerReturn = false;
            }
        }
    }

    /**
     * 加关注
     *
     * @param bean
     */
    @Override
    public void onConcernWith(INetBean bean) {
        if (bean.getErrCode() == 0) {
            if (articleItem == null) {
                return;
            }
            toast(getString(R.string.add_attention_success));
            articleItem.setIsConcern(1);
            AnimationUtil.AlphaScaleAnimator(layout_add_attention, new AnimatorListener() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    layout_add_attention.setVisibility(View.GONE);
                    layout_add_attention.animate().alpha(1).scaleX(1).scaleY(1);
                }
            });
            EventBus.getDefault().post(new AttentionStateChange(articleItem.getIsConcern(), isOtherHomePagerReturn));
        } else {
            toast(bean.getErrMsg());
        }
    }

    /**
     * 推荐支持
     *
     * @param userProps
     */
    @Override
    public void onUserProps(UserProps userProps) {
        if (userProps.getErrCode() == 0) {
            RecommendDialog.Builder builder = new RecommendDialog.Builder(getActivity());
            builder.setPropsCount(userProps.getResponse().getPropsCount())
                    .setContent(recomendContent)
                    .setOnRecommendClickListener(new OnRecommendClickListener() {
                        @Override
                        public void onRecommendClick(int recommend_type, int pay_type, String contents) {
                            postRecommend(recommend_type, pay_type, contents);
                        }

                        @Override
                        public void onDismisssDialog(String contents) {
                            recomendContent = contents;
                        }
                    }).create().show();
        }
    }

    /**
     * 读者推荐
     *
     * @param recommendResponse
     */
    @Override
    public void onPostRecommend(RecommendResponse recommendResponse) {
        if (recommendResponse.getErrCode() == 0) {
            //更新当前单个文章，推荐语
            getRecommendMsg();
        }
        toast(recommendResponse.getErrMsg());
    }

    /**
     * 评论成功返回
     *
     * @param body
     */
    @Override
    public void onPostCommentOrReplyAdd(ResponseBody body) {
        try {
            String json = body.string().toString();
            JSONObject object = new JSONObject(json);
            int errCode = object.getInt("ErrCode");
            String respose = object.getString("Response");
            if (errCode == 0) {
                if (comment_id == 0) {//文章评论
                    CommentDetails details = new Gson().fromJson(json, CommentDetails.class);
                    List<CommentDetails.ResponseBean> beanList = details.getResponse();
                    if (beanList != null && !beanList.isEmpty()) {
                        //本地追加评论
                        CommentDetails.ResponseBean bean = beanList.get(0);
                        //原先评论
                        List<CommentDetails.ResponseBean> beans = new ArrayList<>();
                        beans.addAll(mCommentDetails);
                        //显示评论区，隐藏
                        rv_comment.setVisibility(View.VISIBLE);
                        layout_empty.setVisibility(View.GONE);
                        //清空集合，填充新数据
                        mCommentDetails.clear();
                        mCommentDetails.add(bean);
                        if (!beans.isEmpty()) {
                            mCommentDetails.addAll(beans);
                        }
                        mCommentAdapter.notifyDataSetChanged();
                    }
                    EventBus.getDefault().post(new UpdateCommmentCount(true));
                } else {//评论回复，以及回复的回复
                    List<CommentReplysBean> replysBeans = new Gson().fromJson(respose, new TypeToken<List<CommentReplysBean>>() {
                    }.getType());
                    if (replysBeans != null && !replysBeans.isEmpty()) {
                        //原先的评论回复
                        if (mCommentDetails != null && !mCommentDetails.isEmpty()) {
                            List<CommentReplysBean> list = new ArrayList<>();
                            CommentDetails.ResponseBean bean = mCommentDetails.get(local_position);
                            List<CommentReplysBean> replys = bean.getComment_replys();
                            //重新填充一个集合
                            list.addAll(replys);
                            replys.clear();
                            replys.add(replysBeans.get(0));
                            if (!list.isEmpty()) {
                                //添加以前的数据
                                replys.addAll(list);
                            }
                            //此时，comment_replyCount数量需要增加1
                            int count = bean.getComment_replyCount();
                            count = count + 1;
                            bean.setComment_replyCount(count);
                            mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
                        }
                    }
                }
                toast(comment_id == 0 ? "留言成功" : "回复成功");
                if (comment_id == 0) {
                    if (mScrollY < layout_splendid_comment.getTop() - nested_scroll_view.getMeasuredHeight() + offsetDistance) {
                        nested_scroll_view.smoothScrollTo(0, (int) (layout_splendid_comment.getTop() - (0.8 * offsetDistance)));
                    }
                }
                //清空输入框
                EventBus.getDefault().post(new CleanKeyBoard());
                //清空标识
                cleanIdentifying();
            } else {
                toast(comment_id == 0 ? "留言失败" : "回复失败");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 评论展开
     *
     * @param commentReplysBeans
     */
    @Override
    public void onOnecommentDetail(List<CommentReplysBean> commentReplysBeans) {
        if (mCommentAdapter == null) {
            return;
        }
        mCommentAdapter.getResponseBeanList().get(local_position).setComment_replys(commentReplysBeans);
        mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
    }

    /**
     * 评论点赞返回
     *
     * @param iNetBean
     */
    @Override
    public void onCommentlike(INetBean iNetBean) {
        if (iNetBean.getErrCode() == 0) {
            if (iNetBean.getErrMsg().equals("留言点赞成功")) {
                if (mCommentAdapter != null) {
                    List<CommentDetails.ResponseBean> responseBeanList = mCommentAdapter.getResponseBeanList();
                    if (responseBeanList != null) {
                        int likeCount = responseBeanList.get(likePosition).getLikeCount();
                        responseBeanList.get(likePosition).setLikeCount(likeCount + 1);
                        responseBeanList.get(likePosition).setIslike(1);
                        mCommentAdapter.notifyItemRangeChanged(likePosition, 1, mCommentAdapter.GIVELIKE);
                    }
                }
            }
        } else {
            ToastUtils.show(iNetBean.getErrMsg());
        }
    }

    @Override
    public void onRxjavaSubscribe(Disposable disposable) {
        this.disposable = disposable;
    }

    boolean isFirstInsert = true;

    @Override
    public void onCallBackDealWithContent(String content) {
        String spanned = Html.fromHtml(content).toString();
        if (!TextUtils.isEmpty(spanned)) {
            if (content.contains("<img") && content.contains("src=")) {
                String imagePath = StringUtils.getImgSrc(content);
                txt_content.addImageViewAtIndex(imagePath, isFirstInsert);
            } else {
                isFirstInsert = false;
                txt_content.addTextViewAtIndex(content.trim());
            }
        }
        layout_recommend_details.setVisibility(View.VISIBLE);
    }

    /**
     * 文章评论删除/回复删除
     *
     * @param bean
     */
    @Override
    public void onCommentOrReplyDelete(INetBean bean) {
        if (bean.getErrCode() == 0) {
            if (mCommentAdapter == null) {
                return;
            }
            List<CommentDetails.ResponseBean> responseBeans = mCommentAdapter.getResponseBeanList();
            if (isDeteleReply) {//回复评论
                CommentDetails.ResponseBean response = responseBeans.get(local_position);
                List<CommentReplysBean> replysBeans = response.getComment_replys();
                replysBeans.remove(replyPosition);
                int comment_replyCount = response.getComment_replyCount();
                if (comment_replyCount > 0) {
                    comment_replyCount = comment_replyCount - 1;
                    response.setComment_replyCount(comment_replyCount);
                }
                //如果此时集合中数据和comment_replyCount数据不一致，说明二者数据不一致，需要重新请求
                int replyCount = replysBeans.size();
                if (replyCount < comment_replyCount) {
                    mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
                    getOnecommentDetail(comment_id);//(此处问题在于，如果获取不到数据，当前一条没有更新view)
                } else {
                    mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
                }
            } else {//回复文章
                responseBeans.remove(local_position);
                mCommentAdapter.notifyItemRemoved(local_position);
                mCommentAdapter.notifyItemRangeChanged(local_position, mCommentAdapter.getItemCount() - local_position);
                EventBus.getDefault().post(new UpdateCommmentCount(false));
            }
            int itemCount = mCommentAdapter.getItemCount();
            if (itemCount == 0) {
                pageIndex = 1;
                isLoadMore = false;
                getCommentMsg();
            }
            toast("删除成功");
        } else {
            toast("删除失败");
        }
        //清空输入框
        EventBus.getDefault().post(new CleanKeyBoard());
        //清空标识
        cleanIdentifying();
    }

    /**
     * 清空标识
     */
    private void cleanIdentifying() {
        comment_id = 0;
        reply_id = 0;
        recomendContent = null;
        if (authorDetailBeanMap != null) {
            authorDetailBeanMap.clear();
        }
    }

    /**
     * 分享dialog
     *
     * @param responseBeanList
     */
    private void share(List<PenpalResponse.ResponseBean> responseBeanList) {
        if (articleItem == null) {
            return;
        }

        SharePenpalAndThirdDialog.Builder builder = new SharePenpalAndThirdDialog.Builder(getActivity());
        builder.setType_id(1)
                .setContribute_id(articleItem.getContribute_id())
                .setPenpalwillInfoList(responseBeanList)
                .create().show();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser) {
            hiddon = true;
        } else {
            hiddon = false;
        }
    }

    @Override
    public void onStart() {
        super.onStart();
        EventBus.getDefault().register(this);
    }

    @Override
    public void onStop() {
        super.onStop();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onMessageEventPost(ChangeTextSize data) {
        LogUtil.d("==========>> 收到消息" + data.getTextSize());
        int id = Constant.contentSizes[data.getTextSize()];
        txt_subject.setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) getResources().getDimension(id));
        txt_content.updateRTTextSize((int) getResources().getDimension(id));
    }

    /**
     * 界面切换，评论临时数据清空
     */
    @Subscribe
    public void onPageSelected(CleanCommentEphemeralData data) {
        if (!hiddon) {
            return;
        }
        cleanIdentifying();
    }

    /**
     * 接受分享信息
     */
    @Subscribe
    public void platformToShare(PlatformToShare platform) {
        if (!hiddon) {
            return;
        }
        getPenpalWillMsg();
    }

    /**
     * 接受评论信息
     *
     * @param comment
     */
    @Subscribe
    public void postComment(PostComment comment) {
        if (!hiddon) {
            return;
        }
        if (comment == null) {
            return;
        }
        String content = comment.getContent();
        this.authorDetailBeanMap = comment.getAuthorDetailBeanMap();
        content = Uri.encode(content, "utf-8");
        //发送评论
        postCommentOrReplyAdd(comment_id, reply_id, content);
    }

    /**
     * 滑动到评论区域
     */
    @Subscribe
    public void scrollToCommentDistrict(ScrollToCommentDistrict district) {
        if (!hiddon) {
            return;
        }
        isTouch = true;
        if (lastBodyLocation == 0 && lastCommentLocation == 0) {
            if (mScrollY + nested_scroll_view.getMeasuredHeight() >= layout_splendid_comment.getTop()) {
                LogUtil.i("scrollToCommentDistrict", "原始-------滑动到顶部");
                nested_scroll_view.fullScroll(NestedScrollView.FOCUS_UP);
            } else {
                LogUtil.i("scrollToCommentDistrict", "原始-------滑动到底部");
                nested_scroll_view.smoothScrollTo(0, (int) (layout_splendid_comment.getTop() - (0.8 * offsetDistance)));
            }
        } else {
            if (mScrollY >= layout_splendid_comment.getTop() - nested_scroll_view.getMeasuredHeight() + 1.2 * offsetDistance) {
                if (lastBodyLocation == 0) {
                    LogUtil.i("scrollToCommentDistrict", "非原始---没有记录到正文手动滑动过程----滑动到正文部");
                    nested_scroll_view.fullScroll(NestedScrollView.FOCUS_UP);
                    return;
                }
                LogUtil.i("scrollToCommentDistrict", "非原始---记录到正文手动滑动过程----滑动到正文部");
                nested_scroll_view.smoothScrollTo(0, lastBodyLocation);
            } else {
                if (lastCommentLocation == 0) {
                    LogUtil.i("scrollToCommentDistrict", "非原始---没有记录到评论手动滑动过程----滑动到评论部");
                    nested_scroll_view.smoothScrollTo(0, (int) (layout_splendid_comment.getTop() - (0.8 * offsetDistance)));
                    return;
                }
                nested_scroll_view.smoothScrollTo(0, lastCommentLocation);
                LogUtil.i("scrollToCommentDistrict", "非原始---记录到评论手动滑动过程----滑动到评论部");
            }
        }
    }

    /**
     * 添加关注
     *
     * @param attention
     */
    @Subscribe
    public void addAttention(AddAttention attention) {
        if (!hiddon) {
            return;
        }
        concernWith();
    }

    /**
     * 头像点击
     *
     * @param headerClick
     */
    @Subscribe
    public void onTopHeaderClick(HeaderClick headerClick) {
        if (!hiddon) {
            return;
        }
        onHeaderClick();
    }

    /**
     * 复制，回复，删除评论dialog
     */
    private void showCopyReplyDeleteDialog(final String contents, final String bi_name, final int c_id, final int r_id, int from_uid) {
        if (mCommentAdapter == null) {
            return;
        }
        if (articleItem == null) {
            return;
        }
        //复制，回复，删除
        functions = new ArrayList<>();
        functions.add("复制");
        functions.add("回复");
        //当前登录id
        int user_id = UserInfoUtils.getUserId();
        //当前文章的用户id
        int article_user_id = articleItem.getUser_id();
        //如果(1.登录id==文章的用户id,则是自己的文章，可以删除)(2.如果来自from_uid==登录id，可以删除)
        if (user_id == article_user_id || user_id == from_uid) {
            functions.add("删除");
        }
        BottomListDialog.Builder builder = new BottomListDialog.Builder(getActivity());
        builder.setFunctions(functions)
                .setCancle(getString(R.string.cancle))
                .setCancle_color(R.color.color_2c2c2c)
                .setOption_color(R.color.color_2c2c2c)
                .setOnItemClickListener(new BottomListDialog.Builder.OnItemClickListener() {
                    @Override
                    public void onItemClick(int position, Dialog dialog) {
                        dialog.dismiss();
                        String funtion = functions.get(position);
                        if (funtion.equals("复制")) {
                            ClipboardManager mCM = (ClipboardManager) getContext().getSystemService(CLIPBOARD_SERVICE);
                            mCM.setPrimaryClip(ClipData.newPlainText(null, contents));
                            toast("复制成功");
                        } else if (funtion.equals("回复")) {
                            String replyContent = "回复：" + bi_name;
                            EventBus.getDefault().post(new SetInput(replyContent));
                            comment_id = c_id;
                            reply_id = r_id;
                        } else if (funtion.equals("删除")) {
                            comment_id = c_id;
                            reply_id = r_id;
                            deleteCommentDeleteDialog();
                        }
                    }
                }).create().show();
    }

    /**
     * 删除该条评论提示
     */
    private void deleteCommentDeleteDialog() {
        BanyanDialog.Builder builder = new BanyanDialog.Builder(getContext());
        builder.setTitle("确认要删除该条评论吗？")
                .setLeft("取消")
                .setRight("确定");
        final BanyanDialog dialog = builder.create();
        builder.setDialogOnClick(new BanyanDialog.Builder.onClickListener() {
            @Override
            public void leftClickListener() {
                dialog.dismiss();
            }

            @Override
            public void rightClickListener() {
                dialog.dismiss();
                getCommentOrReplyDelete(comment_id, reply_id);
            }
        });
        dialog.show();
    }

    /**
     * item click
     */
    @Override
    public void onItemClickListener(int position, String contents, String bi_name, int comment_id, int from_uid) {
        this.local_position = position;
        this.isDeteleReply = false;
        showCopyReplyDeleteDialog(contents, bi_name, comment_id, 0, from_uid);
    }

    /**
     * child click
     *
     * @param comment_id
     * @param reply_id
     */
    @Override
    public void onItemChildClickListener(int position, int replyPosition, String contents, String bi_name, int comment_id, int reply_id, int reply_user_id) {
        this.local_position = position;
        this.replyPosition = replyPosition;
        this.isDeteleReply = true;
        showCopyReplyDeleteDialog(contents, bi_name, comment_id, reply_id, reply_user_id);
    }

    /**
     * 展开收缩点击
     */
    @Override
    public void onItemExpandClickListener(boolean isExpanded, int pageSize, int comment_id, int local_position) {
        if (isExpanded) {
            this.isDeteleReply = false;
            this.local_position = local_position;
            getOnecommentDetail(comment_id);
        }
    }

    /**
     * 评论头像点击
     *
     * @param userid
     */
    @Override
    public void onItemHeaderClickListener(int userid, boolean is_allow_browse_homepage) {
        //user_id
        int user_id = getUserId();
        if (user_id == 0) {
            LoginUtils.toLogin((BaseActivity) getActivity(),REQUEST_LOGIN);
            return;
        }
        if (user_id == userid) {
            intent = new Intent(getActivity(), PersonDetailsActivity.class);
        } else {
            intent = new Intent(getActivity(), UserHomePageActivity.class);
            intent.putExtra(Constant.USER_ID, userid);
        }
        startActivity(intent);
    }

    /**
     * 评论点赞
     *
     * @param comment_id
     * @param position
     */
    @Override
    public void onItemGiveLikeClickListener(int comment_id, int position) {
        this.likePosition = position;
        getCommentlike(comment_id);
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        if (disposable != null && !disposable.isDisposed()) {
            disposable.dispose();
        }
    }
}